<?php


namespace wchat\wx;


use wchat\common\Result;

//if (PHP_VERSION > '8.2') {
//    enum Scene
//    {
//
//        case SCENE_INFO;
//        case SCENE_REPLY;
//        case SCENE_DISCAZ;
//        case SCENE_SHEJIAO;
//
//
//        public function getValue(): int
//        {
//            return match ($this) {
//                self::SCENE_INFO    => 1,
//                self::SCENE_REPLY   => 2,
//                self::SCENE_DISCAZ  => 3,
//                self::SCENE_SHEJIAO => 4,
//            };
//        }
//    }
//}


/**
 * Class SecCheck
 * @package wchat
 */
class SecCheck extends SmallProgram
{

    private string $_url             = '/wxa/img_sec_check?access_token=';
    private string $_msgUrl          = '/wxa/msg_sec_check?access_token=';
    private string $_mediaCheckAsync = '/wxa/media_check_async?access_token=';
    const int MEDIA_VIDEO = 1;
    const int MEDIA_IMAGE = 1;

    /**
     * @param string $path
     * @return Result
     */
    public function image(string $path = ''): Result
    {
        if (!file_exists($path)) {
            return $this->sendError('文件不存在', 404);
        }
        $access_token = $this->payConfig->getAccessToken();

        return $this->upload('api.weixin.qq.com', $this->_url . '?access_token=' . $access_token, [
            'media' => new \CURLFile($path)
        ]);
    }


    /**
     * @param string $url
     * @param int $type
     * @return mixed
     * @throws
     */
    public function mediaAsync(string $url, int $type = SecCheck::MEDIA_IMAGE): Result
    {
        if (!in_array($type, [self::MEDIA_IMAGE, self::MEDIA_VIDEO])) {
            throw new \Exception('暂不支持的文件类型');
        }
        $requestUrl = $this->_mediaCheckAsync . $this->payConfig->getAccessToken();

        return $this->post('api.weixin.qq.com', $requestUrl, ['media_url' => $url, 'media_type' => $type]);
    }


    /**
     * @param array $params
     * @return ContentAsyncCheck|null
     */
    public function readByEvent(array $params): ?ContentAsyncCheck
    {
        return ContentAsyncCheck::instance($params);
    }


    /**
     * @param string $content
     * @param int $scene
     * @param string $openId
     * @return Result
     */
    public function text(string $content, int $scene, string $openId): Result
    {
        if (empty($content)) {
            return $this->sendError('文件不存在', 404);
        }
        $requestUrl = $this->_msgUrl . $this->payConfig->getAccessToken();

        return $this->post('api.weixin.qq.com', $requestUrl, json_encode([
            'content' => $content,
            'version' => 2,
            'scene'   => $scene,
            'openid'  => $openId
        ], JSON_UNESCAPED_UNICODE), 'application/json');
    }

}
